package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.login.LoginException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskDetailsService taskDetailsService;
    @Autowired
    private UserService userService;

    //注入EMQ
    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @SneakyThrows
    @Override
    @Transactional
    public boolean createTask(TaskViewModel taskViewModel) {
        //校验工单
        checkCreateTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());
        //校验同一台设备是否有未完成工单
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同一类型工单");
        }
        TaskEntity taskEntity = new TaskEntity();
        //使用生成工单的编号写进taskEntity中
        taskEntity.setTaskCode(generateTaskCode()); //工单编号
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);  //创建待处理
        taskEntity.setProductTypeId(taskViewModel.getProductType());  //工单类型
        //设置执行人名称
        UserVO user = userService.getUser(taskViewModel.getUserId());
        taskEntity.setUserName(user.getUserName());
        //属性复制
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        //工单对应的售货机地址和区域id  --> 跨服务获取
        VmVO vo = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setAddr(vo.getNodeAddr());
        taskEntity.setRegionId(vo.getRegionId());

        //调用保存方法进行工单创建
        this.save(taskEntity);
        //如果补货工单,向工单明细表插入记录
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            taskViewModel.getDetails().forEach(d -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(d, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                //工单明细表中添加补货工单明细
                taskDetailsService.save(detailsEntity);
            });
        }
        //更新工单量列表
        updateTaskZSet(taskEntity, 1);
        return true;
    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean acceptTask(Long id) {
        TaskEntity taskEntity = this.getById(id);       //查询工单
        if (taskEntity.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("该工单不是待处理");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        //修改工单状态为2  --> 接受工单
        return this.updateById(taskEntity);
    }

    /**
     * 取消工单
     *
     * @param id
     * @param cancelTaskViewModel
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelTaskViewModel) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("该工单已经结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        taskEntity.setDesc(cancelTaskViewModel.getDesc());
        //修改工单状态
        boolean update = this.updateById(taskEntity);
        //更新工单量列表
        updateTaskZSet(taskEntity, -1);
        return update;
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单不存在");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        //修改工单为完成状态
        boolean update = this.updateById(taskEntity);
        //如果是撤机或投放工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY
                || taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REPAIR) {
            //运维工单的封装与下发
            noticeVMServiceStatus(taskEntity);
        }
        //如果是补货工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            //补货工单的发送
            noticeVMServiceSupply(taskEntity);
        }
        return update;
    }

    /**
     * 获取同一天内分配的工单最少的人
     *
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002"; //运营工单
        if (isRepair) {
            //运维工单
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId + "." + roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);//获取第一个
        if (set == null || set.isEmpty()) {
            return 0;   //如果没有找到数据就返回0
        }
        return (Integer) set.stream().collect(Collectors.toList()).get(0);
    }

    /**
     * 更新工单量列表
     *
     * @param taskEntity
     * @param score      计算分值  根据员工的工单量计算
     */
    public void updateTaskZSet(TaskEntity taskEntity, int score) {
        //设置roleCode
        String roleCode = "1003";  //运维
        if (taskEntity.getProductTypeId().intValue() == 2) {
            //补货工单
            roleCode = "1002";  //运营人员
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);
    }

    /**
     * 补货工单协议的封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity) {
        //协议内容封装
        //根据工单id查询工单明细表
        /*LambdaQueryWrapper<TaskDetailsEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(queryWrapper);*/
        List<TaskDetailsEntity> details = taskDetailsService.getByTaskId(taskEntity.getTaskId());
        //协议内容
        SupplyContract supplyContract = new SupplyContract();
        //补货编号
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        ArrayList<SupplyChannel> supplyChannels = Lists.newArrayList();
        //工单明细中获取数据加到补货数据中
        details.forEach(d -> {
            SupplyChannel channel = new SupplyChannel();
            //货道编号
            channel.setChannelId(d.getChannelCode());
            //数量
            channel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(channel);
        });
        supplyContract.setSupplyData(supplyChannels);
        //下发补货协议
        //发送消息
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.info("发送工单补货协议出错");
            throw new LogicException("发送工单补货协议出错");
        }
    }

    /**
     * 运维工单的封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        //向消息队列发送消息,通知售货机更改状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());       //售货机编号
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());    //工单类型
        //发送消息
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.info("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 校验同一台设备是否有未完成的工单
     *
     * @param innerCode
     * @param productType
     * @return
     */
    private boolean hasTask(String innerCode, int productType) {
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(queryWrapper) > 0;
    }

    /**
     * 创建工单校验
     *
     * @param innerCode
     * @param productType
     * @throws LoginException
     */
    private void checkCreateTask(String innerCode, int productType) throws LoginException {
        VmVO vmInfo = vmService.getVMInfo(innerCode);       //根据设备编号查询设备
        if (vmInfo == null) {
            throw new LoginException("设备检验失败");
        }
        //如果工单是投放状态,状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }
        //如果工单在补货工单,状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("改设备不在运营状态");
        }
        //如果是撤机工单,状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 生成工单编号的方法
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));//日期字符串
        String key = "lkd.task.code." + date;   //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }


}
